package com.ekuaitu.kuaitu.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.adapter.MyCardAdapter;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.base.BaseActivity;
import com.ekuaitu.kuaitu.base.BaseRcQuickAdapter;
import com.ekuaitu.kuaitu.bean.MyCardBean;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.SharedPreferencesKey;
import com.ekuaitu.kuaitu.utils.SharedPreferencesUtils;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.io.Serializable;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MyCardActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.xr_card)
    XRecyclerView xr_card;
    @BindView(R.id.card_no_view)
    RelativeLayout card_no_view;
    @BindView(R.id.iv_card_return)
    ImageView iv_card_return;
    @BindView(R.id.sw_card)
    SwipeRefreshLayout sw_card;

    @BindView(R.id.title_center)
    RelativeLayout title_center;
    private Context mContext = this;
    private int curPage = 1;
    private MyCardAdapter adapter;
    private int totalDy = 0;
    private boolean isFirstChangeColor = true;

    @Override
    public int getLayoutId() {
        return R.layout.activity_my_card;
    }


    @Override
    public void initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            this.getWindow().setStatusBarColor(Color.TRANSPARENT);
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        }
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        sw_card.setOnRefreshListener(this);
        sw_card.setColorSchemeColors(Color.rgb(70, 200, 120));
        xr_card.setLayoutManager(linearLayoutManager);
        xr_card.setItemAnimator(new DefaultItemAnimator());
        adapter = new MyCardAdapter(mContext, R.layout.item_my_card);
        xr_card.setPullRefreshEnabled(false);
        xr_card.setLoadingMoreEnabled(true);
        xr_card.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {
                curPage++;
                loadNetworkData();
            }
        });
        View header = LayoutInflater.from(this).inflate(R.layout.header_my_card, (ViewGroup) findViewById(android.R.id.content), false);
        final ImageView my_card_header = (ImageView) header.findViewById(R.id.my_card_header);
        my_card_header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "我的彩票");
                if (null != SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.LOTTERY_HISTORY)) {
                    intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.LOTTERY_HISTORY));
                } else {
                    intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlConstant.Request.LOTTERY_HISTORY + SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.USER_PHONE_NUM));
                }
                startActivity(intent);
            }
        });
        xr_card.addHeaderView(header);
        adapter.setOnItemClickListener(new BaseRcQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(mContext, MyCardDetailActivity.class);
                intent.putExtra("cardDetail", (Serializable) adapter.getItem(position));
                startActivity(intent);
            }
        });
        xr_card.setAdapter(adapter);
        iv_card_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        xr_card.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                totalDy += dy;
                Log.i("totalDy", totalDy + "$$$");

                if (totalDy >= 150 && isFirstChangeColor) {
                    isFirstChangeColor = false;
                    title_center.setBackgroundColor(Color.parseColor("#E66341"));
                }
                if (totalDy == 0) {
                    isFirstChangeColor = true;
                    title_center.setBackgroundColor(getResources().getColor(R.color.transparent));
                }
            }

        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        sw_card.measure(0, 0);
        sw_card.setRefreshing(true);
        curPage = 1;
        loadNetworkData();
    }

    private void loadNetworkData() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getCard(MyApplication.getInstance().getRequestFieldMap(), curPage + "", "15").enqueue(new Callback<MyCardBean>() {
            @Override
            public void onResponse(Call<MyCardBean> call, Response<MyCardBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus().equals("200")) {
                        MyCardBean.AttachmentBean result = response.body().getAttachment();
                        if (curPage == 1) {
                            if (result != null && result.getCardCouponModels() != null && result.getCardCouponModels().size() != 0) {
                                adapter.clear();
                                adapter.replaceAll(result.getCardCouponModels());
                                card_no_view.setVisibility(View.GONE);
                                if (sw_card != null) {
                                    sw_card.setRefreshing(false);
                                }
                            } else {
                                if (sw_card != null) {
                                    sw_card.setRefreshing(false);
                                }
                                card_no_view.setVisibility(View.VISIBLE);
                            }
                        } else {
                            if (result != null && result.getCardCouponModels() != null && result.getCardCouponModels().size() != 0) {
                                adapter.addAll(result.getCardCouponModels());
                                xr_card.loadMoreComplete();
                            } else {
                                xr_card.loadMoreComplete();
                            }
                        }

                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<MyCardBean> call, Throwable t) {
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onRefresh() {
        sw_card.measure(0, 0);
        sw_card.setRefreshing(true);
        curPage = 1;
        loadNetworkData();
    }
}
